<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>05-getSnapshotBeforeUpdate使用场景</title>
    <style>
      .newlist {
        width: 300px;
        height: 150px;
        background-color: skyblue;
        overflow: auto;
      }
      li {
        list-style: none;
        height: 30px;
        line-height: 30px;
        box-sizing: border-box;
        border-bottom: 1px solid red;
        
      }
    </style>
  </head>
  <body>
    <div id="app"></div>

    <!-- 导入 react 主库 -->
    <script src="../js/18.2.0/react.development.js"></script>
    <!-- 导入 reactDom 扩展库 -->
    <script src="../js/18.2.0/react-dom.development.js"></script>
    <!-- 导入 babel 用于将jsx转为js -->
    <script src="../js/18.2.0/babel.min.js"></script>
    <!-- 导入 prop-types 用于对组件标签属性进行限制 -->
    <script src="../js/18.2.0/prop-types.js"></script>

    <script type="text/babel">
      class NewsList extends React.Component {
        state = {
          newList: [], // 存放新闻的数组
        };

        componentDidMount() {
          // 制造新闻
          setInterval(() => {
            let { newList } = this.state;
            let news = "新闻" + (newList.length + 1);
            this.setState({
              newList: [news, ...newList],
            });
          }, 1000);
        }

        getSnapshotBeforeUpdate() {
            // 拿到上一次盒子的高度
            // console.log(this.refs.list.scrollHeight);
            return this.refs.list.scrollHeight 
        }

        componentDidUpdate(preProps, preState, height) {
            // this.refs.list.scrollTop = this.refs.list.scrollTop + this.refs.list.scrollHeight - height
            console.log(this.refs.list.scrollTop);
            this.refs.list.scrollTop += this.refs.list.scrollHeight - height
        }

        render() {
          return (
            <div className="newlist" ref='list'>
              {this.state.newList.map((item, index) => {
                return <li key={index}>{item}</li>;
              })}
            </div>
          );
        }
      }
      ReactDOM.render(<NewsList />, document.getElementById("app"));
    </script>
  </body>
</html>
